﻿namespace Vboot.Core.Module.Sys;

public class SysOrgPostService : BaseMainService<SysOrgPost>, ITransient
{
    public SysOrgPostService(SqlSugarRepository<SysOrgPost> repo)
    {
        base.repo = repo;
    }


    public async Task InsertAsync(SysOrgPost post, List<SysOrgPostOrg> pumaps)
    {
        if (post.dept != null)
        {
            post.depid = post.dept.id;
            var deptTier = await repo.Context.Queryable<SysOrgDept>()
                .Where(it => it.id == post.depid).Select(it => it.tier).SingleAsync();
            post.tier = deptTier + post.id + "x";
        }

        repo.Context.Ado.BeginTran();
        await base.InsertAsync(post);
        await repo.Context.Insertable(new SysOrg {id = post.id, name = post.name,type=4}).ExecuteCommandAsync();
        await repo.Context.Insertable(pumaps).ExecuteCommandAsync();
        repo.Context.Ado.CommitTran();
    }


    public async Task UpdateAsync(SysOrgPost post, List<SysOrgPostOrg> pumaps)
    {
        if (post.dept != null)
        {
            post.depid = post.dept.id;
            var deptTier = await repo.Context.Queryable<SysOrgDept>()
                .Where(it => it.id == post.depid).Select(it => it.tier).SingleAsync();
            post.tier = deptTier + post.id + "x";
        }

        repo.Context.Ado.BeginTran();
        await base.UpdateAsync(post);
        await repo.Context.Updateable(new SysOrg {id = post.id, name = post.name,type=4})
            .UpdateColumns(it => new {it.name}).ExecuteCommandAsync();
        await repo.Context.Deleteable<SysOrgPostOrg>().Where(it => it.pid == post.id).ExecuteCommandAsync();
        await repo.Context.Insertable(pumaps).ExecuteCommandAsync();
        repo.Context.Ado.CommitTran();
    }
}